package com.lw.leetcode.binary.c;

/**
 * Created with IntelliJ IDEA.
 * 6098. 统计得分小于 K 的子数组数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/12 13:16
 */
public class CountSubarrays {

    public static void main(String[] args) {
        CountSubarrays test = new CountSubarrays();

        // 6
        int[] arr = {2, 1, 4, 3, 5};
        int k = 10;

        // 5
//        int[] arr = {1, 1, 1};
//        int k = 5;

        long l = test.countSubarrays(arr, k);
        System.out.println(l);
    }

    public long countSubarrays(int[] nums, long k) {
        int length = nums.length;
        long[] arr = new long[length + 1];
        for (int i = 0; i < length; i++) {
            arr[i + 1] = nums[i] + arr[i];
        }
        long sum = 0;
        for (int i = 0; i < length; i++) {
            sum += find(k, arr, i + 1);
        }
        return sum;
    }

    private int find(long t, long[] arr, int end) {
        long v = arr[end] - arr[end - 1];
        if (v >= t) {
            return 0;
        }
        int i = end;
        int st = 1;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            v = (arr[i] - arr[m - 1]) * (i - m + 1);
            if (v >= t) {
                st = m + 1;
            } else {
                end = m;
            }
        }
        return i - st + 1;
    }

}
